<template>
  <el-card class="container">
    <el-row type="flex" justify="space-between" style="margin-bottom: 10px">
      <el-col>
        <el-button size="small" @click="handleBack">返回上一页</el-button>
        <span style="font-weight: bold; margin-left: 10px">{{ title }}</span>
      </el-col>
      <div>
        <el-button type="primary" @click="handleSubmit">提交</el-button>
      </div>
    </el-row>
    <div class="content">
      <el-form :model="formModel" label-width="90px" :rules="rules" ref="form">
        <!-- 员工 -->
        <template>
          <el-card style="margin-bottom: 10px">
            <el-col :span="7">
              <el-form-item label="仓库名称" prop="name">
                <el-input
                style="width: 150px"
                  placeholder="请输入"
                  v-model="formModel.name"
                ></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="7">
              <el-form-item label="仓库编号" prop="code">
                <el-input
                style="width: 150px"
                  placeholder="请输入"
                  v-model="formModel.code"
                ></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="仓库容量" prop="capacity">
                <el-input
                
                  placeholder="请输入"
                  type="number"
                  v-model="formModel.capacity"
                  style="width: 150px"
                >
                  <template slot="append">吨</template>
                </el-input>
              </el-form-item>
            </el-col>
            <el-col :span="24" class="place_container">
              <el-form-item
                :rules="[
                  { required: true, message: '请填写', trigger: 'blur' },
                ]"
                label="企业地址"
              >
                <div style="display: flex; gap: 20px">
                  <el-form-item
                    :rules="[
                      {
                        required: true,
                        message: '请选择省份',
                        trigger: 'change',
                      },
                    ]"
                    prop="province"
                  >
                    <el-select
                    style="width: 150px"
                      v-model="formModel.province"
                      @change="changePro"
                      placeholder="省份"
                    >
                      <el-option
                        v-for="(value, key) in areaList.province_list"
                        :key="key"
                        :label="value"
                        :value="key"
                      >
                      </el-option>
                    </el-select>
                  </el-form-item>
                  <el-form-item
                    :rules="[
                      {
                        required: true,
                        message: '请选择市',
                        trigger: 'change',
                      },
                    ]"
                    prop="city"
                  >
                    <el-select
                    style="width: 150px"
                      v-model="formModel.city"
                      @change="changeCity"
                      placeholder="市"
                    >
                      <el-option
                        v-for="(value, key) in cityList"
                        :key="key"
                        :label="value"
                        :value="key"
                      >
                      </el-option>
                    </el-select>
                  </el-form-item>
                  <el-form-item
                    :rules="[
                      {
                        required: true,
                        message: '请选择区/县',
                        trigger: 'change',
                      },
                    ]"
                    prop="county"
                  >
                    <el-select style="width: 150px" v-model="formModel.county" placeholder="区/县">
                      <el-option
                        v-for="(value, key) in districtList"
                        :key="key"
                        :label="value"
                        :value="key"
                      >
                      </el-option>
                    </el-select>
                  </el-form-item>
                  <el-form-item
                    style="width: 500px"
                    :rules="[
                      {
                        required: true,
                        message: '请填写详细地址',
                        trigger: 'blur',
                      },
                    ]"
                    prop="location"
                  >
                    <el-input
                      v-model="formModel.location"
                      placeholder="详细地址"
                    />
                  </el-form-item>
                </div>
              </el-form-item>
            </el-col>
          </el-card>
          <el-card style="margin-bottom: 10px" v-if="this.userId">
            <el-descriptions title="">
              <el-descriptions-item label="库存状态" span="24">{{
                formModel.statusDesc
              }}</el-descriptions-item>
              <el-descriptions-item label="仓库ID" span="24">{{
                formModel.id
              }}</el-descriptions-item>
              <el-descriptions-item label="创建时间" span="24">{{
                formModel.ctime
              }}</el-descriptions-item>
              <el-descriptions-item label="最后编辑时间" span="24">
                {{ formModel.mtime }}
              </el-descriptions-item>
              <el-descriptions-item label="最后编辑人" span="24">{{
                formModel.modifyUsername
              }}</el-descriptions-item>
            </el-descriptions>
          </el-card>
        </template>
      </el-form>
    </div>
  </el-card>
</template>

<script>
import { userTypeList } from "@/configEnum";
import SelectNameDialog from "@/components/SelectDialog/SelectNameDialog";
import {
  treeselect as menuTreeselect,
  roleMenuTreeselect,
} from "@/api/system/menu";
import { listRole, deptTreeSelect, getRole } from "@/api/system/role";
import { listDept, listDeptChildren } from "@/api/system/dept";
//
import {
  addInventory,
  updateInventory,
  getInventory,
} from "@/api/service/inventory";
import { validatePhoneNumber } from "@/utils";
import { areaList } from "@vant/area-data";

export default {
  components: {
    SelectNameDialog,
  },
  data() {
    return {
      areaList,
      originName: "",
      defaultProps: {
        children: "children",
        label: "label",
      },
      deptOptions: [],
      // 菜单列表
      menuOptions: [],
      rules: {
        nickName: [
          {
            required: true,
            message: "请输入姓名",
            trigger: "change",
          },
        ],
        orgId: [
          {
            required: true,
            message: "请选择机构",
            trigger: "change",
          },
        ],
        deptId: [
          {
            required: true,
            message: "请选择部门",
            trigger: "change",
          },
        ],
        phonenumber: validatePhoneNumber(),
        name: [
          {
            required: true,
            message: "请输入仓库名称",
            trigger: "change",
          },
        ],
        code: [
          {
            required: true,
            message: "请输入仓库编号",
            trigger: "change",
          },
        ],
        capacity: [
          {
            required: true,
            message: "请输入仓库容量",
            trigger: "change",
          },
        ],
        province: [
          {
            required: true,
            message: "请选择",
            trigger: "change",
          },
        ],
        city: [
          {
            required: true,
            message: "请选择",
            trigger: "change",
          },
        ],
        county: [
          {
            required: true,
            message: "请选择",
            trigger: "change",
          },
        ],
        location: [
          {
            required: true,
            message: "请输入详细地址",
            trigger: "change",
          },
        ],
      },
      subAccountTitle: "新增子账号",
      subFormModel: {
        name: undefined,
        userName: undefined,
        phone: undefined,
        status: true,
      },
      subAccountVisible: false,
      subAccountList: [],
      userTypeList,
      formModel: {
        name: "",
        code: "",
        capacity: "",
        province: "",
        city: "",
        county: "",
        location: "",
      },
      sysRole: {
        remark: null,
        roleId: undefined,
        roleName: undefined,
        roleType: undefined,
        roleKey: undefined,
        roleSort: undefined,
        dataScope: 1,
        status: undefined,
        delFlag: undefined,
        flag: undefined,
        menuIds: [],
        deptIds: [],
        permissions: [],
        admin: undefined,
        menuCheckStrictly: true,
        deptCheckStrictly: true,
      },
      roleList: [], // 角色列表
      orgList: [], // 机构列表
      deptList: [], // 部门列表
      deptExpand: true,
      deptNodeAll: false,
      total: 0,
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        subjectId: null,
      },
    };
  },
  watch: {
    userType(n, o) {},
  },
  methods: {
    handleSubmit() {
      this.$refs.form.validate((valid) => {
        if (valid) {
          this.handleValidateSuccess();
        } else {
          return false;
        }
      });
    },
    changePro() {
      this.formModel.city = null;
      this.formModel.county = null;
    },
    changeCity() {
      this.formModel.county = null;
    },
    handleValidateSuccess() {
      //用户
      if (this.formModel.userType === 1) {
        this.formModel.sysRole.menuIds = this.getMenuAllCheckedKeys();
        this.formModel.sysRole.deptIds = this.getDeptAllCheckedKeys();
        // this.formModel.sysRole = this.sysRole;
      }
      console.log(this.formModel);

      if (!this.userId) {
        addInventory({
          ...this.formModel,
        }).then((res) => {
          console.log(res);
          this.handleOkToLink();
        });
      } else {
        updateInventory({
          ...this.formModel,
        }).then((res) => {
          console.log(res);
          this.handleOkToLink();
        });
      }
    },
    handleOkToLink() {
      this.$modal.msgSuccess("操作成功");
      // this.getUserInfo(this.userId);
      this.$router.push({
        path: "/inventory/admin/index",
      });
    },
    handleOrg() {
      // 获取部门列表
      listDeptChildren({
        orgId: this.formModel.orgId,
      }).then((res) => {
        console.log(res);
        this.deptList = res.data;
      });
    },
    /** 查询菜单树结构 */
    getMenuTreeselect() {
      menuTreeselect().then((response) => {
        this.menuOptions = response.data;
      });
    },
    /** 根据角色ID查询部门树结构 */
    getDeptTree(roleId) {
      return deptTreeSelect(roleId).then((response) => {
        this.deptOptions = response.depts;
        return response;
      });
    },
    handleBack() {
      this.$router.push({
        path: "/inventory/admin/index",
      });
    },
    removeSubAccount(row) {
      this.$confirm("确定要删除此账号吗?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          this.$message({
            type: "success",
            message: "删除成功!",
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    getRoleList() {
      /** 查询角色列表 */
      this.loading = true;
      listRole({
        pageNum: 1,
        pageSize: 10000,
      }).then((response) => {
        this.roleList = response.rows;
      });
    },
    /** 查询机构列表 */
    getOrgList() {
      listDept({
        orgType: 1,
      }).then((response) => {
        this.orgList = this.handleTree(response.data, "orgId");
        console.log(this.orgList);
      });
    },
    getUserInfo(userId) {
      if (userId) {
        getInventory(userId).then((response) => {
          console.log("11123", response);
          this.formModel = {
            ...this.formModel,
            ...response.data,
            ...response.sysUserInfo,
          };
          if (response.sysUserInfo.sysRole === null) {
            this.formModel.sysRole = this.sysRole;
          }
          this.handleOrg();
          if (this.formModel.sysRole?.roleId) {
            const roleMenu = this.getRoleMenuTreeselect(
              this.formModel.sysRole.roleId
            );
            getRole(this.formModel.sysRole.roleId).then((response) => {
              this.form = response.data;
              this.open = true;
              this.$nextTick(() => {
                roleMenu.then((res) => {
                  let checkedKeys = res.checkedKeys;
                  checkedKeys.forEach((v) => {
                    this.$nextTick(() => {
                      this.$refs.menu.setChecked(v, true, false);
                    });
                  });
                });
              });
            });
            this.handleDataScope(this.formModel.sysRole.roleId);
          }
          if (this.formModel.userType === 3) {
            // this.getSubList();
          }
        });
      }
    },
    getMenuAllCheckedKeys() {
      // 目前被选中的菜单节点
      let checkedKeys = this.$refs.menu.getCheckedKeys();
      // 半选中的菜单节点
      let halfCheckedKeys = this.$refs.menu.getHalfCheckedKeys();
      checkedKeys.unshift.apply(checkedKeys, halfCheckedKeys);
      return checkedKeys;
    },
    getRoleMenuTreeselect(roleId) {
      return roleMenuTreeselect(roleId).then((response) => {
        this.menuOptions = response.menus;
        return response;
      });
    },
    /** 选择角色权限范围触发 */
    dataScopeSelectChange(value) {
      if (value !== "2") {
        this.$refs.dept.setCheckedKeys([]);
      }
    },
    /** 选择角色权限范围触发 */
    dataScopeSelectChange(value) {
      if (value !== "2") {
        this.$refs.dept.setCheckedKeys([]);
      }
    },
    // 树权限（展开/折叠）
    handleCheckedTreeExpand(value, type) {
      if (type == "menu") {
        let treeList = this.menuOptions;
        for (let i = 0; i < treeList.length; i++) {
          this.$refs.menu.store.nodesMap[treeList[i].id].expanded = value;
        }
      } else if (type == "dept") {
        let treeList = this.deptOptions;
        for (let i = 0; i < treeList.length; i++) {
          this.$refs.dept.store.nodesMap[treeList[i].id].expanded = value;
        }
      }
    },
    // 树权限（全选/全不选）
    handleCheckedTreeNodeAll(value, type) {
      if (type == "menu") {
        this.$refs.menu.setCheckedNodes(value ? this.menuOptions : []);
      } else if (type == "dept") {
        this.$refs.dept.setCheckedNodes(value ? this.deptOptions : []);
      }
    },
    // 树权限（父子联动）
    handleCheckedTreeConnect(value, type) {
      if (type == "menu") {
        this.form.menuCheckStrictly = value ? true : false;
      } else if (type == "dept") {
        this.form.deptCheckStrictly = value ? true : false;
      }
    },
    /** 分配数据权限操作 */
    handleDataScope(roleId) {
      const deptTreeSelect = this.getDeptTree(roleId);
      getRole(roleId).then((response) => {
        this.$nextTick(() => {
          deptTreeSelect.then((res) => {
            this.$refs.dept.setCheckedKeys(res.checkedKeys);
          });
        });
      });
    },
    // 所有部门节点数据
    getDeptAllCheckedKeys() {
      // 目前被选中的部门节点
      let checkedKeys = this.$refs.dept.getCheckedKeys();
      // 半选中的部门节点
      let halfCheckedKeys = this.$refs.dept.getHalfCheckedKeys();
      checkedKeys.unshift.apply(checkedKeys, halfCheckedKeys);
      return checkedKeys;
    },
  },
  created() {
    this.getDeptTree(1);
    this.getMenuTreeselect();
    // 获取机构列表
    this.getOrgList();
    // 获取角色列表
    this.getRoleList();
    this.userId = this.$route.query.id;
    if (this.userId) {
      this.getUserInfo(this.userId);
    }
  },
  computed: {
    cityList() {
      const result = {};
      if (this.formModel.province) {
        Object.keys(this.areaList.city_list).forEach((key) => {
          if (
            +this.formModel.province < +key &&
            +this.formModel.province + 10000 > key
          ) {
            result[key] = this.areaList.city_list[key];
          }
        });
      }
      return result;
    },
    districtList() {
      const result = {};
      if (this.formModel.city) {
        Object.keys(this.areaList.county_list).forEach((key) => {
          if (+this.formModel.city < +key && +this.formModel.city + 100 > key) {
            result[key] = this.areaList.county_list[key];
          }
        });
      }
      return result;
    },
    title() {
      return !this.$route?.query?.id ? "新增仓库" : "修改仓库";
    },
  },
};
</script>

<style lang="scss" scoped>
.tree-border {
  width: 200px;
}
.place_container {
  display: flex;
  .el-form-item {
    margin-right: 10px;
  }
}
.container {
  height: 100%;
  ::v-deep.el-card__body {
    height: 100%;
    display: flex;
    flex-direction: column;
    overflow: hidden;
  }
  .content {
    flex: 1;
    overflow-x: hidden;
    overflow-y: auto;
  }
}
</style>
